import wx
from decimal import Decimal as Dec
import decimal
import sys
import copy

from DataTool import DataTool
from QuotaReader import QuotaReader
from SqlDict import SqlDict
from MyListCtrl import EditableListCtrl

class DiaTable3Change(wx.Dialog):

    TableANames = ['序号', '定额编号', '定额名称', '单位', '普工定额', '技工定额', '普通费率', '拆除费率1', '拆除费率2', '取值说明',]
    TableBNames = ['是否关联', '定额名称', '单位', '仪器仪表/机械', '台班', '单价',]

    ColWidth = [45, 70, 300, 45, 60, 60, 80, 80, 80, 200]
    ColBWidth = [70, 300, 80, 200, 80, 80]

    TableA2Change = [0, 1, 2, 4, 5, -1, -2, -3, 10]
    TableB2Change = [12, 1, 2, 4, 5, 6]

    def __init__(self, parent, title, *args, **kwargs):
        # kwargs 中 datas 为 [[redict, rowdict, teardict], ...]
        self.datas = kwargs.get('datas', [])
        self.indexA, self.indexB, self.indexC = -1, -1, -1
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        # 表三甲
        addquota = EditableListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, name='添加定额', size=(1000,300))
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectedA, addquota)
        self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnLableEditEnd, addquota)

        mainsizer.Add(addquota, 0, flag=wx.ALL|wx.EXPAND, border=5)
        # 机械 仪器仪表列
        nb = wx.Notebook(self,style=wx.NB_TOP|wx.NB_FIXEDWIDTH)
        nbnamelist = ['机械', '仪器仪表', '材料']
        
        for index, name in enumerate(nbnamelist):
            listctrl = EditableListCtrl(nb, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, name=name)
            nb.AddPage(listctrl, name)
            self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnCheckRelated, listctrl)
            self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnClickTable, listctrl)
            self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnLableEditEnd, listctrl)
        mainsizer.Add(nb, 0, flag=wx.ALL|wx.EXPAND, border=5)

        btnsave = wx.Button(self, -1, "保存(&S)")
        btncal = wx.Button(self, -1, "取消(&C)")
        # btntest = wx.Button(self, -1, "TEST(&C)")
        self.Bind(wx.EVT_BUTTON, self.OnSave, btnsave)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, btncal)
        # self.Bind(wx.EVT_BUTTON, self.DisSelectOther, btntest)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        btnsizer.Add((140,20), 1)
        btnsizer.Add(btnsave,0)
        btnsizer.Add((140,20), 0)
        btnsizer.Add(btncal)
        btnsizer.Add((140,20), 1)
        # btnsizer.Add(btntest)

        self.InitListCtrl()
        self.InitImage()

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)

    def OnSave(self, event):
        self.EndModal(retCode=1)

    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.datas
        else:
            return 5101

    def OnSelectedA(self, event):
        obj = self.thistable = event.GetEventObject()
        obj.flag = True
        index = event.GetIndex()
        self.indexA = index
        namelist = ['机械', '仪器仪表']
        tablenamelist = ['表三乙', '表三丙']
        for nameidex, name in enumerate(namelist):
            listctrl = self.FindWindowByName(name)
            listctrl.DeleteAllItems()
            datas = self.datas[index][0][tablenamelist[nameidex]]

            for row, data in enumerate(datas):
                i = listctrl.InsertItem(row, '')
                if data[12] == '0':
                    listctrl.SetItemImage(row, 0)
                else:
                    listctrl.SetItemImage(row, 1)
                for col, ocol in enumerate(self.TableB2Change[1:]):
                    listctrl.SetItem(i, col+1, str(data[ocol]))
        

    def OnCheckRelated(self, event):
        index = event.GetIndex()
        obj = event.GetEventObject()
        obj.flag = True
        name = obj.GetName()
        img_idx = event.GetImage()
        if name == '机械':
            tablename = '表三乙'
        else:
            tablename = '表三丙'
        if img_idx == 1:
            obj.SetItemImage(index, 0)
            self.datas[self.indexA][0][tablename][index][12] = '0'
        elif img_idx == 0:
            obj.SetItemImage(index, 1)
            self.datas[self.indexA][0][tablename][index][12] = '1'

    def OnClickTable(self, event):
        self.thistable = event.GetEventObject()
        obj = event.GetEventObject()
        index = event.GetIndex()
        name = obj.GetName()
        self.DisSelectOther(name)
        self.editend = False
        if name == '机械':
            self.indexB = index
            self.FindWindowByName(name).flag = True
        elif name == '仪器仪表':
            self.indexC = index
            self.FindWindowByName(name).flag = True
        else:
            pass
        self.DisSelectOther(name)
        # event.Skip()

    def OnLableEditEnd(self, event):
        col = event.GetColumn()
        row = event.GetIndex()
        label = event.GetLabel()
        name = self.thistable.GetName()
        if name == '添加定额':
            tablename = '表三甲'
            tableindex = self.TableA2Change
            if tableindex[col - 1] >= 0:
                self.datas[self.indexA][0][tablename][0][tableindex[col - 1]] = label
                if col - 1 == 0:
                    for j in ['表三乙', '表三丙']:
                        for  i in self.datas[self.indexA][0][j]:
                            i[0] = label
            else:
                self.datas[self.indexA][2][- tableindex[col - 1] - 1] = label
        elif name == '机械':
            tablename = '表三乙'
            tableindex = self.TableB2Change
            self.datas[self.indexA][0][tablename][row][tableindex[col]] = label
        else:
            tablename = '表三丙'
            tableindex = self.TableB2Change
            self.datas[self.indexA][0][tablename][row][tableindex[col]] = label
        self.DisSelectOther()

    def DisSelectOther(self, name=None):
        namelist = ['添加定额', '机械', '仪器仪表']
        indexlist = [self.indexA, self.indexB, self.indexC]
        if name is not None:
            try:
                indexlist.pop(namelist.index(name))
                namelist.remove(name)
            except ValueError:
                pass
        for index, name in enumerate(namelist):
            obj = self.FindWindowByName(name)
            obj.Select(-1, 0)
            obj.flag = False


    def InitListCtrl(self):
        namelist = ['添加定额', '机械', '仪器仪表']
        for name in namelist:
            listctrl = self.FindWindowByName(name)
            if name == '添加定额':
                thistablenames = self.TableANames
                thiscolwidth = self.ColWidth
            else:
                thistablenames = self.TableBNames
                thiscolwidth = self.ColBWidth
            # 初始化标签行
            for col, name in enumerate(thistablenames):
                listctrl.InsertColumn(col, name)
                listctrl.SetColumnWidth(col, thiscolwidth[col])
        # 初始化数据
        listctrl = self.FindWindowByName('添加定额')
        listctrl.UnEditCols = [0, 1]
        for row, value in enumerate(self.datas):
            # serial = value[0]['表三甲'][0][0]
            # idnum = value[0]['表三甲'][0][11]
            tear = value[2]
            index = listctrl.InsertItem(row, str(row + 1))
            for col, data in enumerate(self.TableA2Change):
                if data < 0:
                    listctrl.SetItem(index, col+1, str(tear[(-data) - 1]))
                else:
                    listctrl.SetItem(index, col+1, str(value[0]['表三甲'][0][data]))
        
        listctrl.Select(0)
        self.DisSelectOther()
        # listctrl.flag = False
        # if listctrl.GetItemCount() == 1:
        #     thisid = listctrl.GetId()
        #     evt = wx.ListEvent(wx.EVT_LIST_ITEM_SELECTED.typeId, thisid)
        #     evt.SetIndex(0)
        #     wx.PostEvent(listctrl, evt)


    def InitImage(self):
        
        imgsz = (16, 16)
        check_image = self.CreateBitmap(wx.CONTROL_CHECKED, imgsz)
        uncheck_image = self.CreateBitmap(0, imgsz)

        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')
        mater = self.FindWindowByName('材料')
        for i in [mech, meter, mater]:
            i.imagelist = wx.ImageList(*imgsz)
            i.imagelist.Add(uncheck_image)
            i.imagelist.Add(check_image)
            i.AssignImageList(i.imagelist, wx.IMAGE_LIST_SMALL)

        self.__last_check_ = None

    def CreateBitmap(self, flag=0, size=(16, 16)):
        """Create a bitmap of the platforms native checkbox. The flag
        is used to determine the checkboxes state (see wx.CONTROL_*)

        """
        bmp = wx.Bitmap(*size)
        dc = wx.MemoryDC(bmp)
        dc.SetBackground(wx.WHITE_BRUSH)
        dc.Clear()
        wx.RendererNative.Get().DrawCheckBox(self, dc,
                                             (0, 0, size[0], size[1]), flag)
        dc.SelectObject(wx.NullBitmap)
        return bmp

if __name__ == "__main__":
    import os
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            # modal = DiaTable2add(self, 'baba').ShowModal()
            BASE_DIR = os.path.dirname(os.path.abspath(__file__))
            path=os.path.join(BASE_DIR, 'db')
            imagepath=os.path.join(BASE_DIR, 'icon')
            imagepath=os.path.join(imagepath, 'Check')
            imagepath=os.path.join(imagepath, 'Check Icon.png')
            path=os.path.join(path, 'quota.db')
            dia = DiaTable3Change(self, 'haha', path=path, imagepath=imagepath)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()